from rest_framework import serializers
from .models import CartItem
from apps.product.serializers import ProductSerializer, SKUSerializer

class CartItemSerializer(serializers.ModelSerializer):
    product = ProductSerializer(read_only=True)
    sku = SKUSerializer(read_only=True)
    product_id = serializers.IntegerField(write_only=True)
    sku_id = serializers.IntegerField(write_only=True, required=False)
    
    class Meta:
        model = CartItem
        fields = ['id', 'product', 'product_id', 'sku', 'sku_id', 'quantity', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if instance.sku:
            data['price'] = float(instance.sku.price)
            data['stock'] = instance.sku.stock
            data['sku_name'] = instance.sku.name
            data['image'] = instance.sku.image.url if instance.sku.image else instance.product.image.url
        return data 